package com.yq.ylmall.product.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.ylmall.dto.product.ProductUnitQueryDto;
import com.yq.ylmall.model.product.ProductUnit;
import com.yq.ylmall.product.service.IProductUnitService;
import com.yq.ylmall.result.Result;
import com.yq.ylmall.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品单位 后台前端控制器
 * </p>
 *
 * @author yzk789
 * @since 2024-05-30
 */
@RestController
@Api(tags = "商品单位管理接口")
@RequiredArgsConstructor
@RequestMapping("/admin/product/unit")
public class ProductUnitAdminController {

    private final IProductUnitService productUnitService;

    @ApiOperation(value = "分页条件查询商品单位")
    @PostMapping("/page")
    public Result<IPage<ProductUnit>> page(@RequestBody ProductUnitQueryDto dto) {
        Page<ProductUnit> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        productUnitService.page(
                page,
                Wrappers.<ProductUnit>lambdaQuery()
                        .like(StringUtils.hasText(dto.getName()), ProductUnit::getName, dto.getName())
                        .orderByDesc(ProductUnit::getUpdateTime)
        );
        return Result.ok(page);
    }

    @ApiOperation(value = "获取商品单位列表")
    @GetMapping("/all")
    public Result<List<ProductUnit>> list() {
        return Result.ok(productUnitService.list());
    }

    @ApiOperation(value = "商品单位操作：有ID更新，无ID新增")
    @PostMapping("/operate")
    public Result<Object> addUnit(@RequestBody ProductUnit productUnit) {
        boolean success = (productUnit.getId() != null) ? productUnitService.updateById(productUnit) : productUnitService.save(productUnit);
        return success ? Result.ok(ResultCode.SAVE_SUCCESS) : Result.fail(ResultCode.SAVE_FAIL);
    }

    @ApiOperation(value = "删除商品单位")
    @DeleteMapping("/remove/{id}")
    public Result<Object> delUnitById(@PathVariable Long id) {
        boolean deleted = productUnitService.removeById(id);
        return deleted ? Result.ok(ResultCode.DELETE_SUCCESS) : Result.fail(ResultCode.DELETE_FAIL);
    }

    @ApiOperation(value = "批量删除商品单位")
    @DeleteMapping("/remove/batch")
    public Result<Object> delUnitByIds(@RequestBody List<Long> ids) {
        boolean deleted = productUnitService.removeByIds(ids);
        return deleted ? Result.ok(ResultCode.DELETE_SUCCESS) : Result.fail(ResultCode.DELETE_FAIL);
    }

}
